package com.wenyu.wenyuyuedu.activity.personage;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnNetWorkErrorListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.util.RecyclerViewStateUtils;
import com.github.jdsjlzx.view.LoadingFooter;
import com.wenyu.wenyuyuedu.R;
import com.wenyu.wenyuyuedu.activity.LoginActivity;
import com.wenyu.wenyuyuedu.activity.homepage.MyAttentionActivity;
import com.wenyu.wenyuyuedu.adapter.personage.OtherPublicAdapter;
import com.wenyu.wenyuyuedu.bean.personage.MytrendsBean;
import com.wenyu.wenyuyuedu.global.ApiWrapper;
import com.wenyu.wenyuyuedu.server.personage.MytrendsServer;
import com.wenyu.wenyuyuedu.utils.AbSharedUtil;
import com.wenyu.wenyuyuedu.utils.MyToast;
import com.wenyu.wenyuyuedu.utils.SharedConstants;
import com.wenyu.wenyuyuedu.utils.StatusBarUtil;
import com.wenyu.wenyuyuedu.view.CircleImageView;

import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/*
* 他的动态---搜索出来的展示页用
* */
public class OtherPublishActivity extends AppCompatActivity implements View.OnClickListener {
    @InjectView(R.id.header)
    ImageView header;
    @InjectView(R.id.tv_mycircle_titlecontent)
    CircleImageView tvMycircleTitlecontent;
    @InjectView(R.id.tv_mycircle_name)
    TextView tvMycircleName;
    @InjectView(R.id.my_detail_left)
    ImageView myDetailLeft;
    @InjectView(R.id.my_detail_title)
    TextView myDetailTitle;
    @InjectView(R.id.my_detail_right)
    ImageView myDetailRight;
    @InjectView(R.id.toolbar)
    Toolbar toolbar;
    @InjectView(R.id.collapse_toolbar)
    CollapsingToolbarLayout collapseToolbar;
    @InjectView(R.id.list)
    LRecyclerView recyclerView;
    @InjectView(R.id.drawer_layout)
    CoordinatorLayout drawerLayout;
    private Intent intent;
    private Activity activity;
    private LRecyclerViewAdapter lRecyclerViewAdapter;
    private boolean isRefresh = false;
    private int page = 1;
    private Intent intentGet;
    private String userId;
    private List<MytrendsBean.InfoBean> info;
    private OtherPublicAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_other_publish);
        ButterKnife.inject(this);
        StatusBarUtil.setStatusBar(OtherPublishActivity.this, R.color.personage_statue);
        this.activity = OtherPublishActivity.this;
        setupToolbar();
        initView();
        inivLRcyclerView();
        requestData();
    }

    /*初始化recyclerView*/
    private void inivLRcyclerView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(activity));
        recyclerView.setHasFixedSize(true);
        /*创建adapter对象*/
        adapter = new OtherPublicAdapter(activity);
        /*给LRecyclerView的adapter设置adapter*/
        lRecyclerViewAdapter = new LRecyclerViewAdapter(adapter);
        /*给recyclerView设置adapter*/
        recyclerView.setAdapter(lRecyclerViewAdapter);
         /*下拉刷新*/
        recyclerView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                RecyclerViewStateUtils.setFooterViewState(recyclerView, LoadingFooter.State.Normal);
                // adapter.clear();
                //lRecyclerViewAdapter.notifyDataSetChanged();
                isRefresh = true;
                requestData();
            }
        });
        /*加载更多*/
        recyclerView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                if (isRefresh) {
                    return;
                }
                page++;
                requestData();
            }
        });
        /*点击事件*/
        lRecyclerViewAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                intent.setClass(activity, MyAttentionActivity.class);
                String invitationId = info.get(position).getId();
                String title = info.get(position).getTitle();
                intent.putExtra("allattentionnickname", tvMycircleName.getText());
                intent.putExtra("allattentionid", invitationId);
                intent.putExtra("allattentiontitle", title);
                startActivity(intent);
            }
        });
        recyclerView.setFooterViewHint("正在加载中...", "没有更多数据了", "网络请求失败");
        recyclerView.setFooterViewColor(R.color.footview_text_color,R.color.footview_text_color,R.color.footview_back);
    }

    /*获取发表的态*/
    private void requestData() {
        String token = AbSharedUtil.getString(activity, SharedConstants.USER_TOKEN);

        MytrendsServer mytrendsServer = ApiWrapper.getInstance().create(MytrendsServer.class);
        Call<MytrendsBean> mytrends = mytrendsServer.getOtherMytrends(token, page, userId);
        mytrends.enqueue(new Callback<MytrendsBean>() {
            @Override
            public void onResponse(Call<MytrendsBean> call, Response<MytrendsBean> response) {
                MytrendsBean body = response.body();
                if (body != null) {
                    int code = body.getCode();
                    String msg = body.getMsg();
                    if (code == 1) {
                        /*头像*/
                        Glide.with(activity)
                                .load(body.getUserIcon())
                                .error(R.drawable.login_logo)
                                .into(tvMycircleTitlecontent);
                        /*昵称*/
                        tvMycircleName.setText(body.getNickname());
                        info = body.getInfo();
                        if (info.size() == 0) {
                            MyToast.showToast(activity, "没有相关数据", Toast.LENGTH_SHORT);
                        } else {
                            if (isRefresh) {
                                //下拉刷新
                                adapter.clear();
                            }
                            isRefresh = false;
                            adapter.addAll(info);
                            lRecyclerViewAdapter.notifyDataSetChanged();
                        }
                    } else if (code == 0) {
                        //token错误
                        showLoginDoalog();
                    } else if (code == 5000) {
                        //登陆后操作
                        showLoginDoalog();
                    }
                    recyclerView.refreshComplete(page);
                }
            }

            @Override
            public void onFailure(Call<MytrendsBean> call, Throwable t) {
                netError();
                MyToast.showToast(activity, "网络异常，请稍后重试！", Toast.LENGTH_SHORT);
            }
        });
    }

    /*初始化控件*/
    private void initView() {
        intent = new Intent();
        intentGet = getIntent();
        /*用户的id*/
        userId = intentGet.getStringExtra("userid");
        myDetailLeft.setOnClickListener(this);

    }

    /**
     * 网路请求失败时的操作
     */
    private void netError() {
        isRefresh = false;
        recyclerView.refreshComplete(page);
        recyclerView.setOnNetWorkErrorListener(new OnNetWorkErrorListener() {
            @Override
            public void reload() {
                requestData();
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            /*返回*/
            case R.id.my_detail_left:
                finish();
                break;
        }
    }

    /*初始化toolbar*/
    private void setupToolbar() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setHomeButtonEnabled(false);
        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
    }

    /*显示登陆的dialog*/
    private Dialog ad;
    private TextView quxiao;
    private TextView queding;

    private void showLoginDoalog() {
        ad = new android.app.AlertDialog.Builder(activity).create();
        ad.show();
        Window window = ad.getWindow();
        window.setContentView(R.layout.dailog_login);
        quxiao = (TextView) window.findViewById(R.id.dialog_login_quxiao);
        queding = (TextView) window.findViewById(R.id.dialog_login_queding);
        quxiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ad.dismiss();
            }
        });
        queding.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AbSharedUtil.putString(activity, SharedConstants.USER_TOKEN, "");
                Intent intent = new Intent();
                intent.setClass(activity, LoginActivity.class);
                startActivity(intent);
                finish();
                ad.dismiss();
            }
        });
    }
}
